import { _decorator, Texture2D, MeshRenderer, NodePool, sys, geometry, assetManager, Camera, Node, Color, math, Sprite, SystemEvent, LabelComponent, SkinnedMeshRenderer, Prefab, v3, Vec3, SkeletalAnimation, ProgressBar, tween, BoxCollider, ITriggerEvent, RigidBody, PhysicsSystem, Material, EffectAsset } from 'cc';

import BaseView from '../../Script/game/BaseView';
import { Bullet } from '../../Script/config/BaseData';
import Tool from '../../Script/tool/Tool'
// import { luckyBox } from './luckyBox';
import GD from '../../Script/config/GD';
import GDef from '../../Script/config/GDef';
import { classBullet } from '../../Script/game/classBullet';
const { bits } = math;
const { ccclass, property } = _decorator;

@ccclass('preArm')
export class preArm extends BaseView {
    /* class member could be defined like this */
    // dummy = '';

    /* use `property` decorator if your want the member to be serializable */
    // @property
    // serializableDummy = 0;
    private nodeMesh: Node = null;
    private nodeMeshChild: Node = null;
    private nodeArrow: Node = null;
    private nodeHp: Node = null;
    private comCollider: BoxCollider = null;
    private materialNormal: Material = null;
    private materialLight: Material = null;
    private materialHurt: Material = null;
    private scale: number = -1;
    private layerChange: number = -1;
    @property({
        type: Node
    })
    nodeArm: Node = null;
    @property({
        type: Node
    })
    nodeHpPos: Node = null;
    @property({
        type: RigidBody
    })
    comRigidBody: RigidBody = null;
    @property({
        type: Material
    })
    materialNormalSrc: Material = null;
    @property({
        type: Material
    })
    materialLightSrc: Material = null;
    @property({
        type: Material
    })
    materialHurtSrc: Material = null;

    public side: number = 1;//敌我双方：1我方，2敌人
    public __id: number = -1;//对象编号
    public Tid: number = -1;//human或者dino表格的编号
    public cellId: number = -1;//格子编号
    public jsonArmType: Object = null;
    public jsonArm: Object = null;
    public pos: Vec3 = null;
    public eulerAngles: Vec3 = null;
    public hp: number = 0;
    public comHpProgress: ProgressBar = null;
    public nodeEnemy: Node = null;
    public skeletalAnimation: SkeletalAnimation = null;
    public skinnedMeshRenderer: [SkinnedMeshRenderer] = null;
    public collider: BoxCollider = null;
    private baseAni: string = "Idle";//默认动画
    private currentAni: string = null;//默认动画
    public timeLastAttack: number = -10;
    public timeLastChangeTarget: number = -10;
    public runTime: number = 0;
    public intStat: number = 0;//0等待开始,1初始化，2初始化完成，10开始战斗,20死亡
    public isCollide: boolean = false;
    onLoad() {
        this.on(GDef.wdEvent.startFight, this.startFight);
        this.on(GDef.wdEvent.attack, this.attacked);
        this.on(GDef.wdEvent.armDie, this.die);
        this.on(GDef.wdEvent.moveArm, this.moveArm);
        this.on(GDef.wdEvent.releaseArm, this.releaseArm);
        this.on(GDef.wdEvent.setArm, this.setArm);
        this.on(GDef.wdEvent.levelWin, this.playWin);
        // this.on(GDef.wdEvent.levelLose,this.playWin);
        this.intStat = 1;
    }

    /**监听触碰 */
    onTriggerStay(event: ITriggerEvent) {
        // const targetName = event.otherCollider.node.name;
        //遭遇戰
        if (!this.isCollide) this.searchEnemy();
        this.isCollide = true;
    }
    onTriggerExit(event: ITriggerEvent) {
        this.isCollide = false;
    }
    moveArm(cellFrom: number, pos: Vec3) {
        if (this.cellId != cellFrom) return;
        let p = (this.jsonArmType.armType == GDef.TypeHuman ? GDef.getHumanPos(cellFrom) : GDef.getDinoPos(cellFrom));
        this.node.setPosition(v3(pos.x, p.y + 0.5, pos.z));
    }
    releaseArm(cellFrom: number, cellTo: number) {
        if (this.cellId != cellFrom && this.cellId != cellTo) return;
        let from = -1;
        let to = -1;

        if (this.cellId == cellFrom) {
            from = cellFrom;
            to = cellTo;
        }
        else {
            from = cellTo;
            to = cellFrom;
        }

        let pos1 = (this.jsonArmType.armType == GDef.TypeHuman ? GDef.getHumanPos(to) : GDef.getDinoPos(to));
        this.cellId = to;
        this.node.setPosition(pos1);

        GD.setPlayerArm(to, this.jsonArm.armType, this.jsonArm.Tid);

    }
    setArm(cellFrom: number, jsonArm: Object) {
        if (this.cellId != cellFrom) return;
        //消灭部队
        if (jsonArm == null) {
            GD.decPlayerArm(cellFrom);
            GDef.poolArm.put(this.node);
        }
        //合成部队
        else {
            if (GD.intTeach == 1) this.emit(GDef.wdEvent.addTeach);
            this.emit(GDef.wdEvent.playEffect, "Upgrade");
            this.resetModel();
            Tool.playSmoke(this.node.parent.parent, this.node.getPosition());
            GD.setPlayerArm(cellFrom, jsonArm.armType, jsonArm.Tid);
            this.Tid = jsonArm.Tid;
            let jsonArmType = jsonTables.getJsonTableObj(jsonArm.armType == GDef.TypeHuman ? "humanType" : "dinoType", jsonArm.type);
            this.init(this.node.parent, this.side, this.node.position, this.eulerAngles, this.__id, jsonArmType, jsonArm, this.cellId);
            if (jsonArm.armType == GDef.TypeDino) this.emit(GDef.wdEvent.playEffect, "Dinosaur_10" + Math.floor((jsonArm.Tid - 1) / 2));
        }
        this.emit(GDef.wdEvent.updateCoin);
    }
    setScale(n: number) {
        this.scale = n;
    }
    setLayer(n: number) {
        this.layerChange = n;
    }
    playWin() {
        if (this.getStat() == GDef.ArmStatAlive) this.playAni("Win");
    }
    // parent: Node,//父节点
    // public side: number = 1;//敌我双方：1我方，2敌人
    // pos: Vec3,//位置
    // eulerAngles: Vec3//旋转角度,
    // __id: number,//编号
    // Tid: number,//human或者dino表格的编号
    // prefabPackage: string,//预制体包
    // prefabPath: string,//预制体路径
    // modelPackage: string,//模型包
    // modelPath: string//模型路径
    // jsonArmType.Tid,jsonArmType.prefabPackage,jsonArmType.prefabPath,jsonArmType.modelPackage,jsonArmType.modelPath
    init(parent: Node, side: number, pos: Vec3, eulerAngles: Vec3, __id: number, jsonArmType: Object, jsonArm: Object, cellId: number) {
        this.intStat = 1;
        this.side = side;
        this.__id = __id;
        this.cellId = cellId;
        this.jsonArmType = jsonArmType;
        this.jsonArm = jsonArm;
        this.Tid = jsonArm.Tid;
        this.parent = parent;
        this.eulerAngles = eulerAngles;
        this.pos = pos;
        this.nodeEnemy = null;
        this.hp = jsonArm.hp;
        this.comHpProgress = null;
        this.skeletalAnimation = null;
        this.skinnedMeshRenderer = null;
        this.currentAni = null;
        this.timeLastAttack = -10;
        this.runTime = 0;
        this.isCollide = false;
    }
    //初始化節點
    initNode(eulerAngles: Vec3) {
        var self = this;
        let pool = GDef.poolArmModel[(this.jsonArmType.armType == GDef.TypeHuman ? "Hunter" : "Dino") + this.Tid];
        if (!pool) {
            GDef.poolArmModel[(this.jsonArmType.armType == GDef.TypeHuman ? "Hunter" : "Dino") + this.Tid] = new NodePool();
            pool = GDef.poolArmModel[(this.jsonArmType.armType == GDef.TypeHuman ? "Hunter" : "Dino") + this.Tid];
        }
        if (pool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            console.log("通过pool创建");
            this.nodeMesh = pool.get();
            this.initNodeModel(this.eulerAngles);
        }
        else {
            console.log("通过createNode创建");
            if (this && this.jsonArmType && this.jsonArmType.modelPackage) {
                Tool.createNode(this.jsonArmType.modelPackage, this.jsonArmType.modelPath).then((nodeMesh) => {
                    if (self && self.jsonArmType && self.jsonArmType.modelPackage) {
                        console.log("load " + self.jsonArmType.modelPackage + "/" + self.jsonArmType.modelPath);
                        self.nodeMesh = nodeMesh;
                        self.initNodeModel(eulerAngles);
                    }
                    else nodeMesh.destroy();
                });
            }
        }

        //猎人弓箭
        if (this.jsonArmType.armType == GDef.TypeHuman) {
            if (!GDef.poolArmArrowModel[this.Tid]) GDef.poolArmArrowModel[this.Tid] = new NodePool();
            if (this.nodeArrow) {
                GDef.poolArmArrowModel[this.Tid].put(this.nodeArrow);
            }

            if (GDef.poolArmArrowModel[this.Tid].size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                this.nodeArrow = GDef.poolArmArrowModel[this.Tid].get();
                this.initNodeArrow(eulerAngles);
            }
            else {
                Tool.createNode(GDef.pack1, GDef.preBullet).then((node) => {
                    self.nodeArrow = node;
                    self.initNodeArrow(eulerAngles);
                }).catch(err => {
                    console.error(err);
                    return null;
                });
            }
        }
    }
    //初始化人物模型
    initNodeModel(eulerAngles: Vec3) {
        var self = this;
        this.nodeMesh.parent = this.nodeArm;
        //设置layer
        this.node.walk(function (target) {
            if (self.layerChange >= 0) {
                target.layer = self.layerChange;
            }
            else target.layer = self.node.layer;
        });
        this.nodeArm.setRotationFromEuler(eulerAngles);
        this.nodeMesh.scale = v3(this.jsonArmType.scale * 0.001, this.jsonArmType.scale * 0.001, this.jsonArmType.scale * 0.001);
        if (this.scale > -1) this.nodeMesh.scale = v3(this.nodeMesh.scale.x * this.scale, this.nodeMesh.scale.y * this.scale, this.nodeMesh.scale.z * this.scale);
        //加载材质
        this.materialLight = new Material();
        this.materialNormal = new Material();
        this.materialHurt = new Material();
        this.materialLight.copy(this.materialLightSrc);
        this.materialNormal.copy(this.materialNormalSrc);
        this.materialHurt.copy(this.materialHurtSrc);
        if (this && this.jsonArmType && this.jsonArmType.modelPackage) {
            Tool.loadAsset(this.jsonArmType.modelPackage, this.jsonArmType.texturePath + "1/texture", Texture2D).then((texture) => {
                if (self) {
                    //受伤材质
                    self.materialHurt.setProperty("mainTexture", texture);
                    //变异材质
                    if (self.jsonArm.quality == 2) self.materialLight.setProperty("mainTexture", texture);
                    //普通材质
                    else self.materialNormal.setProperty("mainTexture", texture);
                }
            });
        }
        else return;
        //模型
        this.nodeMeshChild = null;
        console.log(this.jsonArmType.name);
        if (this.jsonArmType.armType == GDef.TypeDino) {
            for (let i = 0; i < this.nodeMesh.children.length; i++) {
                if (this.nodeMesh.children[i].name == "meshDino" + this.jsonArmType.Tid) {
                    console.log("set " + this.nodeMesh.children[i].name + " true");
                    this.nodeMeshChild = this.nodeMesh.children[i];
                    this.nodeMesh.children[i].active = true;
                }
                else if (this.nodeMesh.children[i].name.startsWith("mesh")) {
                    console.log("set " + this.nodeMesh.children[i].name + " false");
                    this.nodeMesh.children[i].active = false;
                }
            }
        }
        else {
            this.nodeMeshChild = this.nodeMesh;
        }
        if (this.nodeMeshChild) {
            this.skinnedMeshRenderer = this.nodeMeshChild.getComponentsInChildren(SkinnedMeshRenderer);

            for (let i = 0; i < this.skinnedMeshRenderer.length; i++) {
                //变异
                if (this.jsonArm.quality == 2) {
                    this.skinnedMeshRenderer[i].material = this.materialLight;
                }
                else this.skinnedMeshRenderer[i].material = this.materialNormal;

                this.skinnedMeshRenderer[i].shadowCastingMode = 1;
                this.skinnedMeshRenderer[i].setUseBakedAnimation(true);
            }

            this.meshRenderer = this.nodeMeshChild.getComponentsInChildren(MeshRenderer);

            for (let i = 0; i < this.meshRenderer.length; i++) {
                //变异
                if (this.jsonArm.quality == 2) {
                    this.meshRenderer[i].material = this.materialLight;
                }
                else this.meshRenderer[i].material = this.materialNormal;
                this.meshRenderer[i].shadowCastingMode = 1;
                this.meshRenderer[i].lightmapSettings.bakeable = true;
            }
        }
        //法师特效
        if (this.jsonArmType.armType == GDef.TypeHuman && this.jsonArmType.Tid == 7) {
            Tool.createNode("Hunter7", "fazhang_1/fazhang_1").then((nodeArrow) => {
                nodeArrow.parent = this.nodeMesh.getChildByName("Bip001 Prop2 Socket").getChildByName("meshHunter7_3");
                for (let i = 0; i < nodeArrow.children.length; i++)nodeArrow.children[i].setScale(v3(0.2, 0.2, 0.2));
            })
            Tool.createNode("Hunter7", "fazhang_2/fazhang_2").then((nodeArrow) => {
                nodeArrow.parent = this.nodeMesh.getChildByName("Bip001 Prop1 Socket").getChildByName("meshHunter7_2");
                nodeArrow.setPosition(v3(0, 0, 1.588));
                nodeArrow.setScale(v3(0.2, 0.2, 0.2));
            })
        }

        //贴图
        // for(let i = 0; i < this.skeletalAnimation.clips.length; i++)
        // {
        //     if(this.skeletalAnimation.clips[i].name == "Idle")
        //     {
        //         nodeMesh.getComponent(SkeletalAnimation).defaultClip = this.skeletalAnimation.clips[i];
        //         nodeMesh.getComponent(SkeletalAnimation).playOnLoad = true;
        //         break;
        //     }
        // }
        //碰撞
        this.comCollider = this.nodeArm.addComponent(BoxCollider);
        this.comCollider.enabled = true;
        this.comCollider.setMask(this.side == GDef.SidePlayer ? GDef.GroupEnemy : GDef.GroupPlayer);
        this.comCollider.setGroup(this.side == GDef.SidePlayer ? GDef.GroupPlayer : GDef.GroupEnemy);
        this.comCollider.isTrigger = true;
        this.comCollider.center.x = this.jsonArmType.colliderCenter[0] / 100;
        this.comCollider.center.y = this.jsonArmType.colliderCenter[1] / 100;
        this.comCollider.center.z = this.jsonArmType.colliderCenter[2] / 100;
        this.comCollider.size = v3(this.jsonArmType.colliderSize[0] / 100, this.jsonArmType.colliderSize[1] / 100, this.jsonArmType.colliderSize[2] / 100);
        this.comCollider.on("onTriggerStay", this.onTriggerStay, this);
        this.comCollider.on("onTriggerExit", this.onTriggerExit, this);
        this.isCollide = false;
        //刚体
        if (this.comRigidBody) {
            this.comRigidBody.enabled = true;
        }
        //动画
        this.skeletalAnimation = this.nodeMesh.getComponent(SkeletalAnimation);
        this.skeletalAnimation.stop();
        this.skeletalAnimation.useBakedAnimation = true;
        this.skeletalAnimation.on("finished", this.onAniFinish, this);
        // if (this.skeletalAnimation.clips) {
        //     for(let i = 0; i < this.skeletalAnimation.clips.length; i++)
        //     {
        //         if(this.skeletalAnimation.clips[i].name.startsWith("Attack"))
        //         {
        //             console.warn("找到事件");
        //             this.skeletalAnimation.clips[i].events.push({
        //                 frame: 0.5, // 第 0.5 秒时触发事件
        //                 func: 'onAttackHit', // 事件触发时调用的函数名称
        //                 params: [ 0 ], // 向 `func` 传递的参数
        //             });
        //             this.skeletalAnimation.clips[i].updateEventDatas();
        //         }
        //     }
        // }

        this.playAni("Idle");
        //创建HP
        if (this.nodeHp) {
            this.initHp();
        }
        else {
            if (GDef.poolArmHp.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                this.nodeHp = GDef.poolArmHp.get();
                this.initHp();
            }
            else {
                Tool.createNode(GDef.pack1, GDef.preHp).then((node) => {
                    self.nodeHp = node;
                    self.initHp();
                })
            }
        }
    }
    //初始化弓箭
    initNodeArrow(eulerAngles: Vec3) {
        var self = this;
        //模型
        this.nodeArrow.active = true;
        if (this.nodeArrow) {
            this.nodeArrow.setPosition(self.node.getPosition());
            this.nodeArrow.parent = this.node.parent?.parent?.getChildByName("Bullets");
            this.nodeArrow.scale = v3(0, 0, 0);
            this.nodeArrow.eulerAngles = eulerAngles;
            this.nodeArrow.getComponent(classBullet)?.init(this.jsonArmType, this.jsonArm);
            Tool.createNode(this.jsonArmType.arrowPackage, this.jsonArmType.arrowPath).then((nodeArrow) => {
                self.nodeArrow.getComponent(classBullet)?.setBall(nodeArrow);
            });
        }
    }
    startFight() {
        this.intStat = 10;
    }
    //当前状态
    getStat() {
        return this.hp > 0 ? GDef.ArmStatAlive : GDef.ArmStatDead;
    }
    //被攻击
    attacked(armId: number, damage: number) {
        if (armId != this.__id) return;
        let num = Math.floor(Math.max(0, this.jsonArm.exp * Math.min(this.hp, Math.abs(damage)) / this.jsonArm.hp));
        this.hp = Math.max(0, this.hp - damage);
        if (this.comHpProgress) this.comHpProgress.progress = this.hp / this.jsonArm.hp;
        if (this.hp <= 0 && this.intStat != 20) {
            this.intStat = 20;
            if (this.comCollider) {
                this.comCollider.off("onTriggerStay", this.onTriggerStay, this);
                this.comCollider.off("onTriggerExit", this.onTriggerExit, this);
                this.comCollider.destroy();
                this.comCollider = null;
            }
            if (this.comRigidBody) this.comRigidBody.enabled = false;
            if (this.nodeHp) this.nodeHp.active = false;
            this.playAni("Die");
            let rate = this.jsonArm.eggRate + Math.max(0, (3 - GD.getEggList().length) * 500);
            if (this.jsonArmType.armType == GDef.TypeDino && this.side == GDef.SideEnemy && GD.getEggList().length < 3 && Math.random() * 10000 < rate) Tool.addEgg(this.node, this.jsonArm.Tid);
            this.emit(GDef.wdEvent.armDie, this.__id);
        }
        if (this.side == GDef.SideEnemy) {
            if (num > 0) {
                if (sys.platform === sys.Platform.WECHAT_GAME && wx.vibrateShort) wx.vibrateShort({ type: 'light', style: 'light', fail() { } });
                this.emit(GDef.wdEvent.addCoin, num);
                this.emit(GDef.wdEvent.fightCoin, num);
                Tool.createDamageNumber(num, this);
            }
        }
        //被击发光
        var self = this;
        tween(this.node).call(() => {
            self.setHurt(true);
        }).delay(0.05).call(() => {
            self.setHurt(false);
        }).start();
        //被击特效
        Tool.playAttacked(this.node);
    }
    setHurt(bol: boolean) {
        //被击发光
        if (this.skinnedMeshRenderer) {
            for (let i = 0; i < this.skinnedMeshRenderer.length; i++) {
                if (!bol) {
                    //变异
                    if (this.jsonArm.quality == 2) this.skinnedMeshRenderer[i].material = this.materialLight;
                    else this.skinnedMeshRenderer[i].material = this.materialNormal;
                }
                else this.skinnedMeshRenderer[i].material = this.materialHurt;
            }
        }
        //被击发光
        if (this.meshRenderer) {
            for (let i = 0; i < this.meshRenderer.length; i++) {
                if (!bol) {
                    //变异
                    if (this.jsonArm.quality == 2) this.meshRenderer[i].material = this.materialLight;
                    else this.meshRenderer[i].material = this.materialNormal;
                }
                else this.meshRenderer[i].material = this.materialHurt;
            }
        }
    }
    //某arm死亡
    die(armId: number) {
        if (this.nodeEnemy && this.nodeEnemy.getComponent(preArm).__id == armId) {
            this.nodeEnemy = null;
        }
        if (armId == this.__id) return;
    }
    //发射弓箭
    emitArrow(cb: any = null) {
        if (!this.nodeEnemy) return;
        //初始化子弹信息
        let bullet: Bullet = {
            type: this.jsonArmType.Tid,//猎人类型humanType
            pos: v3(this.node.getPosition().x, this.node.getPosition().y + this.jsonArmType.posArrow[1] / 100, this.node.getPosition().z),//位置
            targetPos: v3(this.nodeEnemy.getPosition().x, this.nodeEnemy.getPosition().y + this.nodeEnemy.getComponent(preArm).jsonArmType.posArrow[1] / 100, this.nodeEnemy.getPosition().z),//位置
            scale: v3(this.jsonArmType.scaleArrow, this.jsonArmType.scaleArrow, this.jsonArmType.scaleArrow),//缩放
            jsonArm: this.jsonArm,
            jsonArmType: this.jsonArmType,
            enemyId: this.nodeEnemy.getComponent(preArm).__id
        };
        console.log("jsonArm:", this.jsonArm);
        var self = this;
        this.scheduleOnce(() => {
            if (self && self.node) {
                self.nodeArrow.active = true;
                self.nodeArrow.getComponent(classBullet)?.startFly(bullet);
            }
        }, 0.3)
    }
    initHp(): void {
        this.comHpProgress = this.nodeHp.children[0].getComponent(ProgressBar);
        Tool.loadSprite(GDef.pack1, this.side == GDef.SidePlayer ? 'img/hpGreen/spriteFrame' : 'img/hpRed/spriteFrame').then((spr) => {
            this.nodeHp.children[0].children[0].getComponent(Sprite).spriteFrame = spr;
        }).catch(err => {
            console.error(err);
        });
        this.nodeHp.parent = GDef.getRoot().getComponent('gameMgr').nodeHpPanel;
        this.nodeHp.scale = v3(0, 0, 0);
        this.hp = this.jsonArm.hp;
        this.comHpProgress.progress = 1;
        this.nodeHp.active = true;
    }
    updateHp(): void {
        if (!this) return;
        if (!this.nodeHp) return;
        if (!this.nodeHp.parent || !this.nodeHp.active) return;
        // console.log("updateHp:" + this.Tid);
        let _v3_0: Vec3 = new Vec3(0, 0, 0);
        let distance: any = (this.node.position.z + 7) * 0.12;
        this.nodeHpPos.setPosition(v3(this.nodeHpPos.position.x, distance * this.jsonArmType.hpY * 0.1, this.nodeHpPos.position.z));
        this.nodeHpPos.getWorldPosition(_v3_0);
        GDef.getCamera().convertToUINode(_v3_0, this.nodeHp.parent, _v3_0);
        this.nodeHp.setPosition(_v3_0);
        this.nodeHp.scale = v3(distance * 0.6, distance * 0.6, distance * 0.6);
    }
    searchEnemy() {
        let nearestNode = null;
        let nearestDistance = bits.INT_MAX;
        let childrens = this.node.parent.children;
        for (let i = 0; i < childrens.length; i++) {
            if (childrens[i].getComponent(preArm).side != this.side && childrens[i].getComponent(preArm).hp > 0) {
                let len: number = Tool.getDistance(childrens[i].position, this.node.position);
                if (len < nearestDistance) {
                    nearestDistance = len;
                    nearestNode = childrens[i];
                }
            }
        }
        this.nodeEnemy = nearestNode;
        return nearestNode;
    }
    doInit() {
        console.log("doinit");
        this.node.setPosition(this.pos);
        this.comRigidBody.enabled = true;
        this.comRigidBody.setMask(this.side == GDef.SidePlayer ? GDef.GroupEnemy : GDef.GroupPlayer);
        this.comRigidBody.setGroup(this.side == GDef.SidePlayer ? GDef.GroupPlayer : GDef.GroupEnemy);
        if (this.comCollider) {
            this.comCollider.off("onTriggerStay", this.onTriggerStay, this);
            this.comCollider.off("onTriggerExit", this.onTriggerExit, this);
            this.comCollider.destroy();
            this.comCollider = null;
        }
        this.initNode(this.eulerAngles);
        this.intStat++;
        if (GD.intTeach == 1 && this.side == GDef.SidePlayer && this.cellId == 26) {
            Tool.showHand(GDef.getRoot(), "tuodong", this.node);
        }
    }
    //逻辑，如果没有敌人则待机，有敌人则移动或者攻击
    doLogic() {
        if (this.hp <= 0) return;

        this.updateHp();
        if (this.nodeEnemy && this.nodeEnemy.getComponent(preArm)?.getStat() == GDef.ArmStatDead) {
            this.nodeEnemy = null;
        }

        if (this.runTime - this.timeLastChangeTarget >= GDef.delayAttack) {
            this.nodeEnemy = null;
            this.timeLastChangeTarget = this.runTime;
        }

        if (!this.nodeEnemy) {
            this.searchEnemy();
        }


        if (this.nodeEnemy) {
            this.nodeArm.lookAt(this.nodeEnemy.getWorldPosition(), v3(0, 1, 0));
            this.nodeArm.setRotationFromEuler(v3(this.nodeArm.eulerAngles.x, this.nodeArm.eulerAngles.y + 180, this.nodeArm.eulerAngles.z));
            //猎人
            if (this.jsonArmType.armType == GDef.TypeHuman) {
                //攻击时刻
                if (this.runTime - this.timeLastAttack >= GDef.delayAttack) {
                    //发射
                    this.playAni("Attack");
                    this.emitArrow(null);
                    this.timeLastAttack = this.runTime;
                }
            }
            //恐龙
            else if (this.jsonArmType.armType == GDef.TypeDino) {
                // // 攻击
                // let dis = Tool.getDistance(this.nodeEnemy.position,this.node.position);
                // if(dis <= GDef.moveSpeed + (this.jsonArmType.size + this.nodeEnemy.getComponent(preArm).jsonArmType.size) / 10)
                if (this.isCollide) {
                    //攻击时刻
                    if (this.runTime - this.timeLastAttack >= GDef.delayAttack) {
                        this.playAni("Attack");
                        this.timeLastAttack = this.runTime;
                        this.nodeEnemy.getComponent(preArm).attacked(this.nodeEnemy.getComponent(preArm)?.__id, this.jsonArm.attack);
                    }
                }
                //移动
                // else if(!this.isCollide)
                else {
                    this.playAni("Run");
                    this.moveTo(this.nodeEnemy.position);
                }
            }
        }
    }
    setBaseAni(name: string) {
        this.baseAni = name;
    }
    playAni(name: string) {
        if (this.skeletalAnimation && this.currentAni != name) {
            console.log("playani:" + name);
            this.currentAni = name;
            this.skeletalAnimation.crossFade(name, 0.1);
        }
    }
    onAttackHit(strEvent: number) {
        console.error("attackHit");
    }
    onAniFinish(strEvent: string, param2: SkeletalAnimationState) {
        if (param2.name != "Win" && param2.name != "Die" && param2.name != this.baseAni && this.hp > 0) {
            this.playAni(this.baseAni);
        }
    }
    moveTo(pos: Vec3) {
        //x*x + y*y = c*c
        //x = y * d
        //y*d*y*d + y*y = c*c
        //y*y*(d*d+1)=c*c
        //y*y=c*c/(d*d+1)
        //y=sqrt(c*c/(d*d+1))
        // console.log("pos:" + pos + ",c:" +c);
        // console.log("this.node.position.x:" + this.node.position.x);
        // let d = 0;
        // if(pos.y - this.node.position.y != 0)d = Math.abs(pos.x - this.node.position.x) / Math.abs(pos.y - this.node.position.y);
        // console.log("d:" + d);
        // // let a = d*b; //a:y,b:x
        // let y = Math.sqrt(c*c/(d*d+1));
        // let x = y * d;
        let disz = pos.z - this.node.position.z;
        let disx = pos.x - this.node.position.x;
        let z = Math.abs(disz);
        let x = Math.abs(disx);
        let xx = 0;
        let zz = 0;
        if (x == 0) zz = GDef.moveSpeed;
        else if (z == 0) xx = GDef.moveSpeed;
        else {
            //xx + zz = 0.1
            //zz = ratio * xx
            //xx + ratio * xx = 0.1
            //xx = 0.1 / (1 + ratio)
            let ratio = z / x;
            xx = GDef.moveSpeed / (1 + ratio);
            zz = ratio * xx;
        }
        if (disx < 0) xx = -xx;
        if (disz < 0) zz = -zz;
        this.node.setPosition(v3(this.node.position.x + xx, this.node.position.y, this.node.position.z + zz));
    }
    onDisable() {
        this.resetModel();
        this.resetData();
    }
    resetModel() {
        let pool = GDef.poolArmModel[(this.jsonArmType.armType == GDef.TypeHuman ? "Hunter" : "Dino") + this.Tid];
        if (!pool) {
            GDef.poolArmModel[(this.jsonArmType.armType == GDef.TypeHuman ? "Hunter" : "Dino") + this.Tid] = new NodePool();
            pool = GDef.poolArmModel[(this.jsonArmType.armType == GDef.TypeHuman ? "Hunter" : "Dino") + this.Tid];
        }
        if (this.nodeMesh) {
            pool.put(this.nodeMesh);
            this.nodeMesh = null;
        }
        if (!GDef.poolArmArrowModel[this.Tid]) GDef.poolArmArrowModel[this.Tid] = new NodePool();
        if (this.nodeArrow) {
            GDef.poolArmArrowModel[this.Tid].put(this.nodeArrow);
            this.nodeArrow = null;
        }

    }
    resetData() {
        if (this) {
            this.nodeHp.active = false;
            if (this.comCollider) {
                this.comCollider.off("onTriggerStay", this.onTriggerStay, this);
                this.comCollider.off("onTriggerExit", this.onTriggerExit, this);
                this.comCollider.destroy();
                this.comCollider = null;
            }
            if (this.comRigidBody) {
                this.comRigidBody.enabled = false;
            }
            if (this.skeletalAnimation) this.skeletalAnimation.off("finished", this.onAniFinish, this);



            this.__id = -1;//对象编号
            this.Tid = -1;//human或者dino表格的编号
            this.cellId = -1;//格子编号
            this.jsonArmType = null;
            this.jsonArm = null;
            this.pos = null;
            this.eulerAngles = null;
            this.hp = 0;
            this.currentAni = null;//默认动画
            this.timeLastAttack = -10;
            this.runTime = 0;
            this.intStat = 0;//0等待开始,1初始化，2初始化完成，10开始战斗
            this.isCollide = false;
        }


    }
    update(deltaTime: number) {
        if (this.intStat == 1) {
            this.runTime += deltaTime;
            this.doInit();
        }
        if (this.intStat == 10) {
            this.runTime += deltaTime;
            this.doLogic();
        }
    }
}
